#!/usr/bin/python3
# -*- coding:utf-8 -*-
import win32api, win32con
import win32clipboard as WC
import time, os
from BladeFerm.hui2_app import FE, driver
from 基础公共脚本.公共方法_hui2 import open_menu, arm_form_fill
from 基础公共脚本.步骤检查_hui2 import check_table, check_table_rows
from qturboframe.lib.utils.by import By
from BladeFerm.Lib.Common import logger
from BladeFerm.Lib.Common import DownPath
from qturboframe.lib.webdriver.exceptions import SeleniumError


def menu_position(input_data=None, ui_expect=None):
    """菜单定位"""
    open_menu(input_data)


class SearchCommon():
    def text_area(self, text=None):
        st=FE.textarea(idname={By.XPATH: '//div[@class="query-from clearfix"]/div/input'})
        st.set_value(text)

    def button(self, text=None):
        FE.button(text=text).click()


class Form():

    def reset(self, input_data=None, ui_expect=None):
        """重置"""
        search_form = FE.form(idname='mainSearch')  # //div/form[@id="mainSearch"]
        search_form.button_option('重置')

    def more(self, input_data=None, ui_expect=None):
        """更多"""
        search_form = FE.form(idname='mainSearch')
        search_form.button_option('更多')

    def form_search(self, input_data=None, ui_expect=None):
        """表单查询"""
        search_form = FE.form(idname='mainSearch')
        try:
            search_form.button_option('更多')
        except:
            logger.debug("无更多按钮")
        search_form.auto_fill(input_data)
        search_form.button_option('查询')


class Table():

    def add_baseInfo(self, input_data=None, lable_name=None):
        """添加按钮_基本信息搜索"""
        is_submit = input_data["是否提交"]
        if is_submit == "提交":
            FE.button(idname={By.XPATH: '//i[@class="h-icon iconfont icon-search h-icon-search"]'}).click()
            # 嵌入搜索表格
            search_form = FE.form(
                idname={By.XPATH: '//div/div[contains(text(),"选择客户")]/parent::div/following-sibling::div/div/form'})
            search_form.button_option('重置')
            search_form.auto_fill(input_data.get(lable_name))
            search_form.button_option('查询')
            self.hyperlinks(idname={
                By.XPATH: '//div/div[contains(text(),"选择客户")]/parent::div/following-sibling::div//div[@class="h-table-wrapper"]'},
                k=list(input_data.get(lable_name).keys())[0], v=list(input_data.get(lable_name).values())[0])

    def add_formInfo(self, input_data=None, lable_name=None):
        """添加按钮_表单信息"""
        is_submit = input_data["是否提交"]
        if is_submit == "提交":
            # 新增表单页
            search_form = FE.form(
                idname={By.XPATH: f'//div/h2[contains(text(),"{lable_name}")]/following-sibling::form'})
            search_form.auto_fill(input_data.get(lable_name))
        FE.button(text=is_submit, idname={
            By.XPATH: '//div[@class="btn-footer"]/button/span[contains(text(),"%s")]' % is_submit}).click()



    def add(self, input_data=None, button_name=None):
        """添加按钮"""
        FE.button(text=button_name, idname=None).click()

    def delete(self, input_data=None, text=None,is_InTable=False,op_TitleName="操作"):
        """
        删除行
        :param is_InTable 删除按钮是否在表格中
        """
        is_delete = input_data["是否提交"]
        input_data.pop("是否提交")
        # FE.table().select_rows(input_data, turn_page=False)
        if is_InTable:
            FE.table().click_button_in_cell(input_data, op_TitleName, text)
        else:
            FE.table().select_rows(input_data, turn_page=False)
            FE.button(text=text, idname=None).click()
        FE.button(text=is_delete, idname={
            By.XPATH: f'//div[@class="h-modal-content"]//div[@class="h-modal-confirm-footer"]/button/span[contains(text(),"{is_delete}")]'}).click()

    def modify(self, input_data=None, text=None):
        '''修改、核查、明细'''
        # 多行
        if "批量" in text:
            FE.table().select_rows(input_data.get("选取行"), turn_page=False)
            FE.button(text=text).click()
        #单行
        else:
            FE.table().click_button_in_cell(input_data.get("选取行"), "操作", text)
        input_data.pop("选取行")

        if text=="修改":
            is_submit = input_data["是否提交"]
            input_data.pop("是否提交")
            if is_submit == "提交":
                search_form = FE.form(
                    idname={By.XPATH: f'//div/h2[contains(text(),"{list(input_data.keys())[0]}")]/following-sibling::form'})
                search_form.auto_fill(list(input_data.values())[0])

            FE.button(text=is_submit,
                      idname={
                          By.XPATH: f'//div[@class="btn-footer"]/button/span[contains(text(),"{is_submit}")]'}).click()
        elif text=="核查" or "核查" in text:
            is_submit = input_data["是否提交"]
            input_data.pop("是否提交")
            FE.button(idname={By.XPATH:f'//div[@class="h-modal-confirm-footer"]/button/span[contains(text(),"{is_submit}")]'}).click()

        elif text=="明细":
            for title in input_data.keys():
                FE.button(idname={
                    By.XPATH: f'//div[@class="result-item"]/h2[contains(text(),"{title}")]'}).click()

    def hyperlinks(self, idname=None, k=None, v=None):
        """
        超链接跳转
        :param k:跳转所在列名
        :param v:跳转钻取点
        """
        FE.table(idname=idname).get_cell({k: v}, title_name=k).click()
    def driver_back(self):
        """返回上一界面"""
        driver.back()



    def export_excel(self, input_data=None, ui_expect=None):
        """导出"""
        logger.debug(f'DownPath： {DownPath}')
        # 进入 风险名单维护查询 菜单
        # open_menu(input_data.get('菜单定位'))
        is_export_all = input_data.get('是否全部')
        input_data.pop("是否全部")
        if is_export_all != '导出全部行':
            # 表格勾选数据
            FE.table().select_row(input_data, turn_page=False)
        # 导出数据
        # FE.button(idname={By.CSS_SELECTOR: 'div.h-dropdown-rel>button'}).click()
        FE.button(
            idname={By.XPATH: '//div[@class="h-dropdown-rel"]/button/span/i[@class="iconfont icon-upload1"]'}).click()
        option_list = FE.list({By.XPATH: '//div[@class="h-dropdown-rel"]//following-sibling::div'})
        option_list.foud_target({By.CSS_SELECTOR: 'button.h-btn'})
        button_name = is_export_all
        option_list.click_target(button_name)

    def download_template(self, k=None, v=None, text=None, ui_expect=None):
        """模板下载
        :param input_data:{"名单导入":"是","模板下载":"是"}
        """
        if v == "是":
            # FE.button(idname={By.CSS_SELECTOR: 'div.h-dropdown-rel>button'},text=text).click()
            FE.button(
                idname={By.XPATH: f'//div[@class="h-dropdown-rel"]/button/span[contains(text(),"{text}")]'}).click()
            FE.button(idname={By.XPATH: f'//ul[@class="h-dropdown-menu"]/li[@class="h-dropdown-item"]/p'}).click()

    def batch_import(self, k=None, v=None, text=None, ui_expect=None):
        """批量导入"""
        # //ul[@class="h-dropdown-menu"]//li[@class="h-dropdown-item"]/div[@class="h-upload"]
        if v == "是":
            FE.button(
                idname={By.XPATH: f'//div[@class="h-dropdown-rel"]/button/span[contains(text(),"{text}")]'}).click()
            try:
                UploadFile().uploadByInput(idname={By.XPATH: '//input[@class="h-upload-input"]'}, path=k)
            except:
                FE.button(idname={
                    By.XPATH: f'//ul[@class="h-dropdown-menu"]//li[@class="h-dropdown-item"]/div[@class="h-upload"]'}).click()
                UploadFile().uploadFile(k)


class Tag:
    def tag_click(self, tag_name=None):
        """标签进去"""
        FE.tag({By.XPATH: f'//div[@class="h-tabs-nav"]/div[contains(text(),"{tag_name}")]'}).click()

    def tag_form(self, form_name=None, input_data=None):
        """标签页表单定位"""

        form1 = FE.form(idname={By.XPATH: f'//h2[contains(text(),"{form_name}")]/following-sibling::div/form'})
        form1.auto_fill(input_data)
        form1.button_option('查询')
        form1.button_option('重置')


class Check():
    def check_rows(self, input_data=None, ui_expect=None):
        """检查查询结果"""
        check_table_rows(input_data=input_data, ui_expect=ui_expect)

    def check_export(self, input_data=None, ui_expect=None):
        """导出校验"""
        # 检查导出结果
        box = FE.msg_box(idname={By.XPATH: '//div[@class="h-modal-wrap h-modal-nocopy"]'}, timeout=1)
        box.check_dispaly(ui_expect.get('期望结果') == '是')
        # 等待导出弹框关闭
        if box.element:
            box.check_export_result(True)


class UploadFile():
    """上传文件"""

    def getText(self):
        """获取剪切板的内容"""
        WC.OpenClipboard()
        value = WC.GetClipboardData(win32con.CF_TEXT)
        WC.CloseClipboard()
        return value

    def setText(self, value):
        """设置剪切板的内容"""
        WC.OpenClipboard()
        WC.EmptyClipboard()
        WC.SetClipboardData(win32con.CF_UNICODETEXT, value)
        WC.CloseClipboard()

    def uploadFile(self, filePath):
        """
        上传文件
        使用 python 的 win32api，win32con 模拟按键输入，实现文件上传操作。
        :param webEle: 页面中的上传文件按钮,是已经获取到的对象
        :param filePath: 要上传的文件地址，绝对路径。如：D:\\timg (1).jpg
        """
        # pyperclip.copy(filePath)  # 复制文件路径到剪切板
        self.setText(filePath)  # 待上传文件设置到剪切板

        time.sleep(3)  # 等待程序加载 时间 看你电脑的速度 单位(秒)
        # 发送 ctrl（17） + V（86）按钮
        win32api.keybd_event(17, 0, 0, 0)
        win32api.keybd_event(86, 0, 0, 0)
        win32api.keybd_event(86, 0, win32con.KEYEVENTF_KEYUP, 0)  # 松开按键
        win32api.keybd_event(17, 0, win32con.KEYEVENTF_KEYUP, 0)
        time.sleep(1)
        win32api.keybd_event(13, 0, 0, 0)  # (回车)
        win32api.keybd_event(13, 0, win32con.KEYEVENTF_KEYUP, 0)  # 松开按键
        win32api.keybd_event(13, 0, 0, 0)  # (回车)
        win32api.keybd_event(13, 0, win32con.KEYEVENTF_KEYUP, 0)
        time.sleep(2)

    def uploadByInput(self, idname=None, path=None):
        """通过input-file标签上传文件"""
        by = list(idname.keys())[0]
        value = list(idname.values())[0]
        driver.find_element(by=by, value=value).send_keys(f"{path}")
